package juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/*
Semaphore演示
6辆车（线程），3个车位（许可证）
 */
public class SemaphoreDemo {

  public static void main(String[] args) {

//    创建许可证
    java.util.concurrent.Semaphore semaphore = new java.util.concurrent.Semaphore(3);

    for (int i = 1; i <= 6 ; i++) {
      new Thread(()->{

        try {
//          请求
          semaphore.acquire();

          System.out.println(Thread.currentThread().getName() + "抢到了车位");
//          等待
          TimeUnit.SECONDS.sleep(new Random().nextInt(5));

          System.out.println(Thread.currentThread().getName() + "---离开了车位");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }finally {
//          释放
          semaphore.release();
        }

      },String.valueOf(i)).start();
    }

  }
}
